var express = require('express');
var router = express.Router();
const sql = require('../sql/sql')
const pro = require('../sql/pro')
const  xlsx = require('node-xlsx')
const uuid = require('node-uuid')


router.get('/', function(req, res, next) {
  let num = 10;
  let index = 0;
  sql.page(pro,{},{},num,index).then(data=>{
    sql.count(pro).then(maxNum=>{
      res.render('pro',{
        i:1,
        data,
        maxPage:Math.ceil(maxNum/num),
        pageIndex:index,
        num
      })
    })
  })
});

router.get("/upload",function(req,res,next){
  const obj = xlsx.parse("./data/pro2.xlsx");
  let arr = [];
  for(let i=1;i<obj[0].data.length;i++){
    arr.push({
      proId:"pro"+uuid.v1(),
      proName:obj[0].data[i][1],
      column:obj[0].data[i][2],
      brand:obj[0].data[i][3],
      logo:obj[0].data[i][4],
      proImg:obj[0].data[i][5],
      price:obj[0].data[i][6],
      introduce:obj[0].data[i][7],
      stock:obj[0].data[i][8],
      sales:obj[0].data[i][9],
      discount:obj[0].data[i][10],
      score:obj[0].data[i][11],
      store:obj[0].data[i][12],
      freight:obj[0].data[i][13],
      seckill:obj[0].data[i][14]
    })
  }
  sql.insert(pro,arr).then(()=>{
    res.redirect("/pro");
  })
})


router.get("/page",function(req,res,next){
  const { num, index  } = req.query;
  sql.page(pro,{},{},num-0,index-0).then(data=>{
    sql.find(pro,{}).then(data2=>{
      res.render('pro', { 
        i: 1,
        data,
        pageIndex:index-0,
        num,
        maxPage:Math.ceil(data2.length/num)
      });
    })
  })
})


module.exports = router;
